<template>
  <div class="register">
    <div class="simple-title">
      <span>{{ hexAddress }}</span>
      <el-divider></el-divider>
    </div>
    <el-form label-width="auto" :model="floatRegister" @submit.native.prevent="">
      <el-form-item label="Float AB CD:" class="form-item">
        <el-input v-model.number="floatRegister.floatABCD">
          <template #append>
            <span>({{ getFloatHex(floatRegister.floatABCD) }})</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Float CD AB:" class="form-item">
        <el-input v-model.number="floatRegister.floatCDAB">
          <template #append>
            <span>({{ getFloatHex(floatRegister.floatCDAB) }})</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Float BA DC:" class="form-item">
        <el-input v-model="floatRegister.floatBADC">
          <template #append>
            <span>({{ getFloatHex(floatRegister.floatBADC) }})</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Float DC BA:" class="form-item">
        <el-input v-model="floatRegister.floatDCBA">
          <template #append>
            <span>({{ getFloatHex(floatRegister.floatDCBA) }})</span>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="LongRegister" lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import {type FloatPointRegister } from "@/types/register";
// import { editPointData } from "@/api/deviceApi";
import 'element-plus/dist/index.css'
import { TableHeader } from "@/types/device";
import { useRegisterStore } from "@/stores/register";
const registerStore = useRegisterStore();

const props = defineProps({
  registers: { type: Object, required: true },
  isDualRegister: { type: Boolean, required: true },
});

// 核心地址转换逻辑
const hexAddress = computed(() => {
  if (!props.isDualRegister) {
    // 单寄存器处理（完全匹配图片示例）
    const addr = props.registers[TableHeader.Address];
    return registerStore.formatHex(addr);
  } else {
    // 双寄存器处理（用"-"连接）
    if (!Array.isArray(props.registers)) {
      console.error('Dual decode_register mode requires array input');
      return '';
    }
    return props.registers
      .map(reg => registerStore.formatHex(reg[TableHeader.Address]))
      .join('-');
  }
});

const floatRegister = ref<FloatPointRegister>({
  floatABCD: 0,
  floatCDAB: 0,
  floatBADC: 0,
  floatDCBA: 0,
  value: 0,
});

// 浮点数转16进制（处理负数和小数）
const getFloatHex = (value:number) =>{
  const buffer = new ArrayBuffer(4);
  const view = new DataView(buffer);
  view.setFloat32(0, value, false); // 大端序写入
  const hex = view.getUint32(0, false) // 保持大端序读取
    .toString(16)
    .toUpperCase()
    .padStart(8, '0');
  return "0x" + hex;
}

function updateFromValue(value: number) {
  // 计算原始浮点数值
  const floatValue = value;

  // 将浮点数转换为32位二进制表示（IEEE 754标准）
  const buffer = new ArrayBuffer(4);
  const view = new DataView(buffer);
  view.setFloat32(0, floatValue, false); // 大端序写入

  // 生成四种字节序排列（仅操作二进制位，不改变浮点结构）
  floatRegister.value = {
    floatABCD: view.getFloat32(0, false),  // 原始大端序浮点值
    floatCDAB: new DataView(reorderBytes(buffer, 'CDAB')).getFloat32(0, false),
    floatBADC: new DataView(reorderBytes(buffer, 'BADC')).getFloat32(0, false),
    floatDCBA: new DataView(reorderBytes(buffer, 'DCBA')).getFloat32(0, false),
    value: value
  };
}

// 字节序重排工具函数
function reorderBytes(buffer: ArrayBuffer, type: 'CDAB' | 'BADC' | 'DCBA') {
  const view = new DataView(buffer);
  const uint32 = view.getUint32(0, false);
  const newBuffer = new ArrayBuffer(4);
  const newView = new DataView(newBuffer);

  switch(type) {
    case 'CDAB':
      newView.setUint32(0,
        ((uint32 & 0xFFFF0000) >>> 16) |
        ((uint32 & 0x0000FFFF) << 16), false);
      break;
    case 'BADC':
      newView.setUint32(0,
        ((uint32 & 0xFF00FF00) >>> 8) |
        ((uint32 & 0x00FF00FF) << 8), false);
      break;
    case 'DCBA':
      newView.setUint32(0,
        ((uint32 & 0xFF000000) >>> 24) |
        ((uint32 & 0x00FF0000) >>> 8) |
        ((uint32 & 0x0000FF00) << 8) |
        ((uint32 & 0x000000FF) << 24), false);
  }
  return newBuffer;
}

const setFloatRegisterValue = (registers: any) => {
  const [v1, v2] = registers.slice(0, 2).map((r: { [x: string]: number; }) => r[TableHeader.RegisterValue] || 0);
  const hex = v1.toString(16).padStart(4, '0') + v2.toString(16).padStart(4, '0');

  // 使用DataView直接解析为Float32
  const buffer = new ArrayBuffer(4);
  const view = new DataView(buffer);
  view.setUint32(0, parseInt(hex, 16));

  floatRegister.value.value = view.getFloat32(0);
}

watch (() => props.registers, (newVal, oldVal) => {
  setFloatRegisterValue(newVal);
  updateFromValue(floatRegister.value.value);
});

onMounted(() => {
  setFloatRegisterValue(props.registers);
  updateFromValue(floatRegister.value.value);
});
</script>

<style lang="scss" scoped>
.register {
  margin: 2px;
  padding: 10px;
  width: 420px;
  font-family: Arial, sans-serif;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0.2, 0.2, 0.2, 0.2);
}

.simple-title {
  text-align: center;
}
.simple-title span {
  font-size: 16px;
  color: #409eff;
  font-weight: 500;
}
.simple-title .el-divider {
  margin: 12px 0;
  background-color: #409eff;
}

.form-item {
  width: 400px;
  margin: 5px;
}

.custom-row {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}
</style>
